package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.service.UserService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;

/**
 * 用户模块控制层
 * @author wangxin
 * @version 1.0
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Reference
    private UserService userService;

    /**
     * 获取当前登录用户的用户名
     */
    @RequestMapping("/getUsername")
    @PreAuthorize("isAuthenticated()")
    public Result getUsername(){
        //.getContext().安全容器对象
        //getAuthentication():认证对象
        //.getPrincipal();当前用户对象 user
        try {
            User user = (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            return new Result(true, MessageConstant.GET_USERNAME_SUCCESS,user.getUsername());
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_USERNAME_FAIL);
        }
    }

    /**
     * 分页查询用户管理的数据
     * @return
     */
    @RequestMapping(value = "/findPage")
    @PreAuthorize("hasAnyAuthority('USER_QUERY')")
    public Result findPage(@RequestBody QueryPageBean queryPageBean) {
        try {
            PageResult userPage = userService.findPage(queryPageBean);
            return new Result(true, MessageConstant.GET_USERMANAGE_SUCCESS, userPage);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_USERMANAGE_FAIL);

        }
    }

    /**
     * 根据id获得用户对象
     */
    @RequestMapping("/findById")
    @PreAuthorize("hasAnyAuthority('USER_EDIT')")
    public Result findById(Integer id){
        try {
            com.itheima.pojo.User user = userService.findById(id);
            return new Result(true,MessageConstant.GET_USERMANAGE_SUCCESS,user);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.GET_USERMANAGE_FAIL);
        }
    }
    /**
     * 根据id获得用户角色ids
     */
    @RequestMapping("/findRoleIds")
    @PreAuthorize("hasAuthority('USER_EDIT')")
    public Result findRoleIds(Integer userId){
        try {
            List<Integer> roleIds = userService.findRoleIds(userId);
            return new Result(true,MessageConstant.GET_ROLEMANAGEIDS_LIST_SUCCESS,roleIds);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.GET_ROLEMANAGEIDS_LIST_FAIL);
        }
    }

    /**
     * 添加用户信息
     */
   @RequestMapping(value = "/add")
   @PreAuthorize("hasAuthority('USER_ADD')")
    public Result add(@RequestBody com.itheima.pojo.User user,Integer[] roleIds){
       try {
           userService.add(user,roleIds);
           return new Result(true,MessageConstant.ADD_USERMANAGE_SUCCESS);
       } catch (Exception e) {
           e.printStackTrace();
           return new Result(false,MessageConstant.ADD_USERMANAGE_FAIL);
       }
   }

    /**
     * 删除用户信息
     */
    @RequestMapping("/delete")
    @PreAuthorize("hasAuthority('USER_DELETE')")
    public Result delete(Integer id){
        try {
            userService.delete(id);
            return new Result(true,MessageConstant.DELETE_USERMANAGE_SUCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.DELETE_USERMANAGE_FAIL);
        }
    }

    /**
     * 编辑用户信息
     */
    @RequestMapping("/edit")
    @PreAuthorize("hasAuthority('USER_EDIT')")
    public Result edit(@RequestBody com.itheima.pojo.User user,Integer[] roleIds) {
        try {
            userService.edit(user,roleIds);
            return new Result(true,MessageConstant.EDIT_USERMANAGE_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.EDIT_USERMANAGE_FAIL);
        }
    }

    /**
     * 更改用户状态
     */
    @RequestMapping("/changeStationByUsername")
    @PreAuthorize("hasAuthority('USER_STATION')")
    public Result changeStationByUsername(String username,String station) {
        try {
            if (station != null && station.equals("1")) {
                //如果传递的状态是正常,则修改成冻结
                station = "0";
            } else if (station != null && station.equals("0")){
                //如果传递的状态是冻结,则修改成正常
                station = "1";
            } else {
                return new Result(false,MessageConstant.EDIT_STATION_ILLEGAL);
            }
            HashMap<String, String> param = new HashMap<>();
            param.put("station",station);
            param.put("username",username);
            userService.changeStationByUsername(param);
            if (station.equals("1")) {
                return new Result(true,MessageConstant.EDIT_USERSTATION_FREEZE_SUCCESS);
            } else {
                return new Result(true,MessageConstant.EDIT_USERSTATION_UNFREEZE_SUCCESS);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.EDIT_USERSTATION_FAIL);
        }
    }

    /**
     * 重置密码
     */
    @RequestMapping("/changePassword")
    @PreAuthorize("hasAuthority('USER_RESETPASSWORD')")
    public Result changePassword(String username) {
        try {
            //校验数据
            if (username == null) {
                return new Result(false, MessageConstant.ILLEGAL_OPTATION);
            }
            String telephoneByUsername = userService.findTelephoneByUsername(username);
            String password = telephoneByUsername.substring(telephoneByUsername.length() - 6);
            BCryptPasswordEncoder bCrypt = new BCryptPasswordEncoder();
            password = bCrypt.encode(password);
            //封装数据
            HashMap<String, String> param = new HashMap<>();
            param.put("username", username);
            param.put("password", password);
            //修改密码
            userService.changePassword(param);
            return new Result(true, MessageConstant.RESET_USERPASSWPRD_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(true, MessageConstant.RESET_USERPASSWPRD_FAIL);
        }
    }
    /**
     * 修改密码
     */
    @PreAuthorize("hasAuthority('USER_CHANGEPASSWORD')")
    @RequestMapping("/updatePassword")
    public Result updatePassword(@RequestBody HashMap<String,String> param){
        try {
            //校验数据
            String oldPassword = param.get("oldPassword");
            String newPassword = param.get("newPassword");
            if (oldPassword == null || newPassword == null) {
                return new Result(false, MessageConstant.ILLEGAL_OPTATION);
            }
            //得到当前用户校验密码是否正确
            User user = (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            BCryptPasswordEncoder bCrypt = new BCryptPasswordEncoder();
            //通过方法查询该账户原来的密码
            com.itheima.pojo.User pojoUser = userService.findByUserName(user.getUsername());
            if (bCrypt.matches(oldPassword, pojoUser.getPassword())){
                //密码正确,修改密码
                param.put("username",user.getUsername());
                param.put("password",bCrypt.encode(newPassword));
                userService.changePassword(param);
            } else {
                //密码不正确,抛出异常
                return new Result(false,MessageConstant.PASSWORD_ERRO);
            }
            return new Result(true,MessageConstant.EDIT_USERPASSWPRD_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.EDIT_USERPASSWPRD_FAil);
        }
    }

    /**
     * 校验新增用户名是否存在
     */
    @RequestMapping(value = "/findByName")
    public Result findByName(String userName){
      com.itheima.pojo.User byUserName = userService.findByUserName(userName);
      if (byUserName!=null){
          return new Result(false,MessageConstant.GET_USEREXIST_FAil);
      }
      return new Result(true,null);
    }
}
